<template>
  <view class="container">
    <uv-sticky>
      <view class="operate-bar" v-if="editMode">
        <uv-checkbox-group>
          <uv-checkbox :name="true" label="全选" @change="toggleSelectAll" v-model="selectAll">全选
            {{ selectedList.length > 0 ? `(${selectedList.length})` : '' }}
          </uv-checkbox>
        </uv-checkbox-group>
        <uv-button type="primary" icon="plus" iconColor="#3c9cff" size="mini" plain @click="batchAssign">批量下发
        </uv-button>
      </view>
      <view class="search-box">
        <uv-search @change="changeFn" placeholder="请输入任务名" :show-action="false" :border="false" bgColor="#FFFFFF" borderColor="#d8d8d8"
                   v-model="queryParams.taskName" shape="square" :clearabled="true" @clear="clear"></uv-search>

        <uv-drop-down
            ref="dropDown"
            sign="dropDown_1"
            :extra-icon="{name:'arrow-down-fill',color:'#666',size:'26rpx'}"
            :extra-active-icon="{name:'arrow-up-fill',color:'#3c9cff',size:'26rpx'}"
            :defaultValue="defaultValue"
            :custom-style="{padding: '0 100rpx'}"
            @click="selectMenu"
        >
          <uv-drop-down-item
              name="area"
              type="2"
              :label="dropItem('area').label"
              :value="dropItem('area').value">
          </uv-drop-down-item>
          <uv-drop-down-item
              name="type"
              type="2"
              :label="dropItem('type').label"
              :value="dropItem('type').value">
          </uv-drop-down-item>
        </uv-drop-down>
        <uv-drop-down-popup
            sign="dropDown_1"
            :click-overlay-on-close="true"
            :currentDropItem="currentDropItem"
            @clickItem="clickItem"
            @popupChange="change"
        ></uv-drop-down-popup>

      </view>
    </uv-sticky>

    <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
      <div class="list-item" v-for="(item, index) in dataList" :key="index">

        <div class="flex">
          <view class="item-checkbox" v-if="editMode">
            <uv-checkbox-group>
              <uv-checkbox
                  :name="item.id"
                  :checked="selectedList.includes(item.id)"
                  @change="checkboxChange(item.id)"
              ></uv-checkbox>
            </uv-checkbox-group>
          </view>
          <uv-text :lines="2" :text="item.title" bold></uv-text>

          <view>
            <!--  任务周期 -->
            <uv-text v-for="dict in taskCycleData"
                     :key="dict.dictKey"
                     v-if="item.cycle == dict.dictKey"
                     :text="dict.dictValue"
                     :type="dict.listClass"
            ></uv-text>
            <!-- 任务类型 -->
            <uv-text v-for="dict in taskTypeData"
                     :key="dict.dictKey"
                     v-if="item.timeType == dict.dictKey"
                     :text="dict.dictValue"
                     :type="dict.listClass"
            ></uv-text>
          </view>
        </div>
        <div class="flex">
          <uv-album :urls="item.sampleGraph" maxCount="3"
                    multipleSize="100rpx"
                    singleSize="100rpx"
                    space="8rpx" :previewFullImage="false"></uv-album>
          <view>
            <div class="text-gray ">下发人：{{ item.realName }}</div>
            <div class="text-gray ">执行截止：{{ item.deadline }}</div>
            <div class="text-gray ">检查截止：{{ item.inspectDeadline }}</div>
          </view>

        </div>
        <div class="flex">
          <div class="text-gray ">上次下发：{{ item.lastTime }}</div>
          <div @tap="goDetail(item)">
            <uv-button type="primary" text="下发" size="mini"></uv-button>
          </div>
        </div>
      </div>
    </mescroll-body>

    <uni-fab ref="fab" :pattern="{icon:'settings'}" horizontal="right" :content="content" @trigger="trigger">
    </uni-fab>
  </view>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";

import TaskAPI from '@/api/task'
import {rexTime} from "@/utils/media";
import AreaAPI from "@/api/area";
import DictAPI from "@/api/dict";

export default {
  onPageScroll() {
    // 滚动后及时更新位置
    this.$refs.dropDown.init();
  },
  computed: {
    dropItem(name) {
      return (name) => {
        const result = {};
        const find = this.result.find(item => item.name === name);
        if (find) {
          result.label = find.label;
          result.value = find.value;
        } else {
          result.label = this[name].label;
          result.value = this[name].value;
        }
        return result;
      }
    },
    // 获取当前下拉筛选项
    currentDropItem() {
      return this[this.activeName];
    }
  },
  mixins: [MescrollMixin], // 使用mixin
  comments: {},
  watch: {
    selectedList: {
      handler(newVal) {
        // 当所有项都被选中时自动勾选全选
        this.selectAll = newVal.length === this.dataList.length && this.dataList.length > 0;
      },
      deep: true
    }
  },
  data() {
    return {
      editMode: false, // 编辑模式
      selectedList: [], // 选中的ID集合
      selectAll: false,// 全选状态
      checkboxValue: [],
      // 表示value等于这些值，就属于默认值
      defaultValue: [0, 'all', '0'],
      // 筛选结果
      result: [],
      // { name: 'order', label: '最新发布', value: 'new' }
      activeName: 'area',
      area: {
        label: '区域',
        value: 'all',
        activeIndex: 0,
        color: '#333',
        activeColor: '#2878ff',
        child: []
      },
      type: {
        label: '任务周期',
        value: 'all',
        activeIndex: 0,
        color: '#333',
        activeColor: '#2878ff',
        child: []
      },
      current: 0,
      queryParams: {
        current: 1,
        size: 10,
        areaIds: '',
        cycle: ''
      },
      dataList: [],
      total: 0,
      show: false,
      form: {},
      authority: 'employee', // admin、employee、purchase、employee_manager、purchase_manager
      taskCycleData: [],
      taskTypeData: [],
      content: [{
        iconPath: '/static/task/edit.png',
        selectedIconPath: '/static/task/cancel.png',
        text: '批量',
        active: false
      },
        {
          iconPath: '/static/task/add.png',
          selectedIconPath: '/static/task/add.png',
          text: '新增',
          active: false
        }
      ]
    }
  },
  onLoad(e) {
    this.authority = uni.getStorageSync('authInfo')?.authority
    this.getFilterCriteria()
  },
  methods: {
    checkboxChange(id) {
      const index = this.selectedList.indexOf(id);
      if (index > -1) {
        this.selectedList.splice(index, 1);
      } else {
        this.selectedList.push(id);
      }
    },
    trigger(e) {
      if (e.index === 0) {
        this.content[0].active = !e.item.active
        this.content[0].text = !e.item.active ? '取消' : '批量'
        this.editMode = !e.item.active
        if (!this.editMode) {
          this.selectedList = []
          this.selectAll = false
        }
      } else if (e.index === 1) {
        uni.navigateTo({
          url: `/subpackage/task/add`
        });
      }
    },

    // 全选/反选
    toggleSelectAll(e) {
      this.selectAll = e;
      if (this.selectAll) {
        this.selectedList = this.dataList.map(item => item.id);
      } else {
        this.selectedList = [];
      }
    },

    async batchAssign() {
      if (this.selectedList.length === 0) {
        return uni.showToast({title: '请选择任务', icon: 'none'})
      }
      uni.navigateTo({
        url: `/subpackage/task/add?ids=${this.selectedList.join(',')}`
      });
    },

    getFilterCriteria() {
      AreaAPI.tree(1).then(res => {
        this.area.child = res.data.map(item => {
          return {
            label: item.title,
            value: item.id
          }
        })
        this.area.child.unshift({
          label: '全部',
          value: 'all'
        })
      })

      DictAPI.dictByCodeList({code: 'task_time_type'}).then(res => {
        this.taskTypeData = res.data
      })

      DictAPI.dictByCodeList({code: 'task_cycle'}).then(res => {
        this.taskCycleData = res.data
        this.type.child = res.data.map(item => {
          return {
            label: item.dictValue,
            value: item.dictKey
          }
        })
        this.type.child.unshift({
          label: '全部',
          value: 'all'
        })
      })
    },
    change(e) {
      console.log('弹窗打开状态：', e);
    },
    /**
     * 点击每个筛选项回调
     * @param {Object} e { name, active, type } = e
     */
    selectMenu(e) {
      const {name, active, type} = e;
      this.activeName = name;
      // type 等于1 的需要特殊处理：type不等于1可以忽略
      const find = this.result.find(item => item.name === this.activeName);
      if (find) {
        this[this.activeName].activeIndex = this[this.activeName].child.findIndex(item => item.label === find.label && item.value === find.value);
      } else {
        this[this.activeName].activeIndex = 0;
      }
    },
    /**
     * 点击菜单回调处理
     * @param {Object} e 选中项 { label,value } = e
     */
    clickItem(e) {
      // 下面有重新赋值，所以用let
      let {label, value} = e;
      const findIndex = this.result.findIndex(item => item.name === this.activeName);
      if (this.defaultValue.indexOf(value) > -1 && this[this.activeName].label) {
        label = this[this.activeName].label;
      }
      // 已经存在筛选项
      if (findIndex > -1) {
        this.$set(this.result, findIndex, {
          name: this.activeName,
          label,
          value
        })
      } else {
        this.result.push({
          name: this.activeName,
          label,
          value
        });
      }
      this.result = this.result.filter(item => this.defaultValue.indexOf(item.value) === -1);

      this.queryParams.areaIds = this.result.find(item => item.name === 'area')?.value || ''
      this.queryParams.cycle = this.result.find(item => item.name === 'type')?.value || ''
      this.changeFn()
    },

    goDetail(item) {
      uni.navigateTo({
        url: `/subpackage/task/assign?id=${item.id}`
      })
    },
    /*上拉加载的回调*/
    upCallback(page) {
      let me = this
      me.queryParams.current = page.num; // 页码, 默认从1开始
      TaskAPI.taskList(me.queryParams).then(res => {
        let curPageData = res.data.records
        // 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
        let curPageLen = curPageData.length;
        // 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
        let totalPage = res.data.totalPage
        me.total = res.data.total
        //设置列表数据
        if (page.num === 1) this.dataList = []; //如果是第一页需手动置空列表

        curPageData.forEach(item => {
          item.sampleGraph = item.sampleGraph?.split(',')
          item.lastTime = item.lastTime ? rexTime(item.lastTime) : '--'

          let title = ''
          if (item.areaName) {
            title = item.areaName + '-'
          }
          if (item.taskName) {
            title += item.taskName
          }
          item.title = title
        })

        this.dataList = this.dataList.concat(curPageData); //追加新数据

        // 请求成功,隐藏加载状态
        //方法一(推荐): 后台接口有返回列表的总页数 totalPage
        this.mescroll.endByPage(curPageLen, totalPage);
      })
    },

    // 重置选择条件
    reset() {
      this.content[0].active = false
      this.content[0].text = '批量'
      this.editMode = false
      this.selectedList = []
      this.selectAll = false
    },

    changeFn() {
      this.reset()

      let me = this;
      me.queryParams.current = 1
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    clear() {
      this.queryParams = {
        current: 1,
        size: 10
      }
      this.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
  }
}
</script>

<style>
.list-item {
  width: 85%;
  margin: 0.3rem auto;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 操作栏样式 */
.operate-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.flex {
  display: flex;
  justify-content: space-between;
  line-height: 1.4rem;
  margin-top: 10rpx;
}

.text-gray {
  font-size: 14px;
  color: gray;
  margin: 0.2rem 0;
}

.def-user {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-right: 80rpx;
}
</style>